<!--
  Author wln
  Version 1.0.1
  Date 2021年1月7日16:32:02
  Desc 表单用上传文件、图片
  Editor --
-->
<template>
	<div>

		<!-- 文件上传 -->
		<div class="upload-file" v-if="type == 'file'">
			<div class="upload-btn" v-if="!disabled">
				<div class="btn">
					<el-button type="primary" size="small" @click="fileBtnClick" :loading="loading">选择文件</el-button>
					<input
							type="file"
							:multiple="multiple"
							:accept="accept"
							class="file-input"
							@change="fileChange"
							:id="'fileUpload_' + random"
							title=""
							:disabled="disabled || loading"
					>
				</div>
			</div>
			<div class="file-list" v-if="showFileList">
				<div class="file-item" v-for="(item,index) in currentFileList">
					<div class="file-msg">
						<i class="el-icon-document"></i>
						<span v-if="fileCanClick" class="file-name" @click="fileClick(item)" style="cursor: pointer">{{item.name}}</span>
						<span v-else class="file-name">{{item.name}}</span>
					</div>
					<div class="right-icon">
						<i class="el-icon-circle-check"></i>
						<i class="el-icon-close" v-if="!disabled" @click="fileDelete(index)"></i>
					</div>
				</div>
			</div>
		</div>

		<!-- 图片/视频上传 -->
		<div class="upload-image" v-else-if="type == 'image' || type == 'video'">
			<!-- 多选 -->
			<div class="mutiple-image" v-if="multiple">
				<div class="img-list">
					<div class="upload-btn" v-if="multiple && !disabled">
						<img v-if="!loading" src="../../assets/images/upload.png" alt="点击选择文件" class="add-image">
						<img v-else src="../../assets/images/5-121204193R5-50.gif" alt="点击选择文件" class="loading-image">
						<input
								type="file"
								class="image-input"
								multiple
								@change="(e) => {imageChange(e,'mutiple')}"
								:accept="accept == '*' || accept == '' ? type == 'image' ? 'image/jpg,image/jpeg,image/png,image/gif' : 'video/mp4' : accept"
								:id="'mediaUpload_' + random"
								title=""
								:disabled="disabled || loading"
								ref="imageInputMultiple"
						>
					</div>
					<div class="img-item" v-for="(item,index) in currentFileList"
						 :style="{width: type == 'video' ? 'auto' : '100px'}">
						<video v-if="type == 'video'" :src="ftpDownload + item.path" style="height: 100%;"
							   @click="filePreview(index)"></video>
						<el-image v-else :src="ftpDownload + item.path" fit="cover" class="img"
								  @click="filePreview(index)"></el-image>
						<div class="delete" @click="fileDelete(index)" v-if="!disabled">
							<img src="../../assets/images/delImg.png" alt="">
						</div>
					</div>
				</div>
			</div>
			<!-- 单选 -->
			<div class="signle-upload-btn upload-btn" v-else>
				<video v-if="currentFileList.length > 0 && type == 'video'" :src="ftpDownload + currentFileList[0].path"
					   style="max-height: 100%;max-width: 100%"></video>

				<el-image v-if="currentFileList.length > 0 && type == 'image'"

						  :src="ftpDownload + currentFileList[0].path" fit="cover" class="img"></el-image>
				<img v-if="!loading" src="../../assets/images/upload.png" alt="点击选择文件" class="add-image">
				<img v-else src="../../assets/images/5-121204193R5-50.gif" alt="点击选择文件" class="loading-image">
				<div class="opera" v-if="currentFileList.length > 0">
					<div class="delete" v-if="!disabled">
						<el-tooltip effect="light" content="修改" placement="right">
							<i class="el-icon-edit" @click="fileEdit"/>
						</el-tooltip>
					</div>
					<div class="view">
						<el-tooltip effect="light" content="预览" placement="right">
							<i class="el-icon-zoom-in" @click="filePreview(0)"/>
						</el-tooltip>
					</div>
				</div>
				<div class="top-delete" v-if="currentFileList.length > 0 && !disabled" @click="fileDelete(0)">
					<img src="../../assets/images/delImg.png" alt="">
				</div>
				<input
						ref="imageInput"
						class="image-input"
						:class="currentFileList.length > 0 ? 'he50' : ''"
						type="file"
						@change="(e) => {imageChange(e,'single')}"
						:id="'mediaUpload_' + random"
						:accept="accept == '*' || accept == '' ? type == 'image' ? 'image/jpg,image/jpeg,image/png,image/gif' : 'video/mp4/AVI/wma/rmvb/rm/flash/mid/3GP' : accept"
						title=""
						:disabled="disabled"
				>
			</div>
		</div>
		<!-- 图片预览 -->
		<image-viewer
				:z-index="999999"
				:initial-index="view.initialIndex"
				v-if="view.visible && type == 'image'"
				:on-close="closeViewer"
				:url-list="view.previewSrcList"
		/>
		<!-- 视频预览 -->
		<video-viewer
				:z-index="999999"
				:initial-index="view.initialIndex"
				v-if="view.visible && type == 'video'"
				:on-close="closeViewer"
				:url-list="view.previewSrcList"
		/>
	</div>
</template>

<script>
	const axios = require('axios');
	import {getToken, getFtpCs, getFtpCk} from '@/utils/auth';
	import ImageViewer from 'element-ui/packages/image/src/image-viewer';
	import VideoViewer from '@/components/BcVideoViewr';
	import {randomString} from '@/utils/bc-tool-data';

	export default {
		name: 'BcForm',
		components: {
			ImageViewer,
			VideoViewer
		},
		props: {
			dataBind: null,
			nameBind: '',
			pathBind: '',
			uploadDiskPath: '',
			maxSize: {
				type: Number,
				default: 0
			},
			max: {
				type: Number,
				default: 0
			},
			type: {
				type: String,
				default: 'file'
			},
			multiple: {
				type: Boolean,
				default: false
			},
			showFileList: {
				type: Boolean,
				default: true
			},
			accept: {
				type: String,
				default: '*'
			},
			upImg: {
				type: String,
				default: '/pri/malfunctionStock/recovery_upload'
			},
			acceptSuffix: {
				type: String,
				default: ''
			},
			fileCanClick: {
				type: Boolean,
				default: true
			},
			disabled: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				loading: false,
				currentFileList: [],
				uploadFileList: [],
				view: {
					initialIndex: 0,
					visible: false,
					previewSrcList: []
				},
				ftpDownload:process.env.NODE_ENV === 'production' ?
						process.env.VUE_APP_BASE_API + '/files' :
						process.env.VUE_APP_BASE_HOST + process.env.VUE_APP_BASE_API + '/files',
				ftpUpload: process.env.VUE_APP_BASE_API,
				random: ''
			};
		},
		watch: {
			// currentFileList: {  // 监听会造成数据混乱， 因为这里非法修改父级数据
			//   handler: function (val) {
			//     let name = [],
			//       path = [],
			//       previewSrcList = []
			//     val.forEach(item => {
			//       name.push(item.name)
			//       path.push(item.path)
			//       previewSrcList.push(this.ftpDownload + item.path)
			//     })
			//     this.dataBind[this.nameBind] = name.join(',')
			//     this.dataBind[this.pathBind] = path.join(',')
			//     this.view.previewSrcList = previewSrcList
			//   }
			// },
			// 处理回显数据
			dataBind: {
				handler: function (val) {
					this.dealBackFile();
				},
				immediate: true
			}
		},
		created() {
			console.log(this.ftpDownload,666,this.$store.getters.ftpInfo)
			// 随机字符串
			this.random = randomString();
		},

		methods: {
			// 回显处理
			dealBackFile() {
				console.log('走了吗',this.dataBind)
				// 回显要拿路径处理，因为图片没有存储name字段
				if (this.dataBind[this.pathBind] == '') {
					this.currentFileList = [];
				} else {
					let name = !this.dataBind[this.nameBind] ? [] : this.dataBind[this.nameBind],
							path = !this.dataBind[this.pathBind] ? [] : this.dataBind[this.pathBind],
							fileList = [];
					console.log('path',path);
					console.log('name',name)
					if (path.length > 0) {
						path.forEach((item, index) => {
							let lastIndex = item.lastIndexOf("/")
							let filename = item.substr(lastIndex + 1)
							fileList.push({
								name: name[index] ? name[index] : filename,
								path: item,
								showPath: this.ftpDownload + path[index],
								file: null,

							});
						});
					}
					this.currentFileList = fileList;
					this.dealParentData();
				}
			},

			// 选择文件按钮
			fileBtnClick() {
				document.getElementById('fileUpload_' + this.random).click();
			},

			// 选择文件
			fileChange(e) {
				let files = e.target.files;
				if (this.multiple) {
					this.dealFiles('multiple', files);
				} else {
					this.dealFiles('single', files);
				}
				// 文件上传
				this.uploadFile().then(() => {
					document.getElementById('fileUpload_' + this.random).value = '';
				});
			},

			// 点击文件名
			fileClick(data) {
				if (data.path) {
					window.open(this.ftpDownload + data.path);
				} else {
					this.$message({
						type: 'warning',
						message: '文件未提交，不能预览'
					});
				}
			},

			// 选择图片/视频
			imageChange(e, type) {
				let files = e.target.files;
				switch (type) {
					case 'single':
						this.dealFiles('single', files);
						break;
					case 'mutiple':
						this.dealFiles('mutiple', files);
						break;
				}
				// 文件上传
				this.uploadFile().then(() => {
					document.getElementById('mediaUpload_' + this.random).value = '';
				});
			},

			// 处理文件
			dealFiles(type, files) {
				this.uploadFileList = [];
				if (type == 'single') {
					this.currentFileList = [];
					if (this.maxSize > 0) {
						if (files[0].size > this.maxSize) {
							this.$message.error('文件大小超出限制范围');
							return;
						}
					}
					// 单选
					this.uploadFileList = [{
						name: files[0].name,
						file: files[0],
						path: '',
						showPath: ''
					}];
				} else {
					let big = 0,
							repeat = 0;
					for (let i = 0; i < files.length; i++) {
						// 去重
						let mark = 0;
						// 在已上传文件列表中去重
						for (let j = 0; j < this.currentFileList.length; j++) {
							if (this.maxSize > 0) {
								if (files[i].size > this.maxSize) {
									mark++;
									big++;
								}
							}
							if (files[i].name == this.currentFileList[j].name) {
								mark++;
								repeat++;
							}
						}
						// 填充数组
						if (mark == 0) {
							this.uploadFileList.push({
								name: files[i].name,
								path: '',
								file: files[i],
								showPath: ''
							});
						}
					}
					this.violation('file', big, repeat);
					// 数量限制
					if (this.max > 0) {
						if (this.uploadFileList.length > this.max) {
							this.uploadFileList = this.uploadFileList.splice(0, this.max);
							setTimeout(() => {
								this.$message({
									message: `最多可选择${this.max}个文件,超出部分已被删除`,
									type: 'warning'
								});
							}, 200);
						}
					}
				}
			},

			// 单图片/视频修改
			fileEdit() {
				document.getElementById('mediaUpload_' + this.random).click();
			},

			// 删除
			fileDelete(index) {
				this.$confirm('删除该文件, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.currentFileList.splice(index, 1);
					this.dealParentData();
					this.$emit('delImage',index)
				}).catch(err => {

				});
			},

			// 预览图片/视频
			filePreview(index) {
				this.view.visible = true;
				this.view.initialIndex = index;
			},

			// 关闭预览图片/视频
			closeViewer() {
				this.view.visible = false;
			},

			// 违规反馈
			violation(type, big, repeat) {
				let message = '个文件';
				if (type == 'image') {
					message = '张图片';
				} else if (type == 'video') {
					message = '个视频';
				}
				if (big > 0) {
					this.$message({
						message: `${big}${message}大小超出限制范围，已被删除`,
						type: 'warning'
					});
				}
				if (repeat > 0) {
					if (big > 0) {
						setTimeout(() => {
							this.$message({
								message: `${repeat}${message}重复选择，已被删除`,
								type: 'warning'
							});
						}, 100);
						return;
					}
					this.$message({
						message: `${repeat}${message}重复选择，已被删除`,
						type: 'warning'
					});
				}
			},

			// 上传
			uploadFile() {
				return new Promise(async (resolve, reject) => {
					if (!this.uploadDiskPath) {
						reject('uploadDiskPath is undefined');
						return;
					}
					if (this.uploadFileList.length == 0) {
						resolve('无需上传文件');
						return;
					}
					this.loading = true;
					let files = [];
					for (let i = 0; i < this.uploadFileList.length; i++) {
						if (this.uploadFileList[i].file) {
							files.push(this.uploadFileList[i]);
						}
					}
					if (files.length > 0) {
						const xhr = new XMLHttpRequest();
						const param = new FormData();
						// 上传文件地址
						param.append('ftpFileToDiskPath', this.uploadDiskPath);
						for (let i = 0; i < files.length; i++) {
							param.append('files', files[i].file);
						}
						const config = {
							headers: {'Content-Type': 'multipart/form-data'}
						};
						config.headers['token'] = getToken();
						xhr.open('post', this.ftpUpload + this.upImg, true);
						xhr.send(param);
						xhr.onreadystatechange = () => {
							if (xhr.status == 200 && xhr.readyState == 4) {
								let res = JSON.parse(xhr.response);
								console.log('res----------',res)
								if (res.code == 1) {
									// res.data.forEach(sitem => {
									this.currentFileList.push({
										file: null,
										name: res.data.filename,
										path: res.data.path,
										fileId:res.data.fileId
									});
									// });
									this.dealParentData();
									this.loading = false;
									// 清除当前验证
									if (this.currentFileList.length > 0) {
										try {
											this.$parent.clearValidate();
										} catch (e) {
											console.log('try catch() 捕获的错误: 用于重置表单项，单独使用组件时可忽略');
											console.log(e);
										}
									}
									resolve('上传成功');
								}
							}
						};
					}
				});

			},

			// 处理父级数据
			dealParentData() {
				let name = [],
						path = [],
						fileIds=[],
						previewSrcList = [];
				this.currentFileList.forEach(item => {
					name.push(item.name);
					path.push(item.path);
					fileIds.push(item.fileId)
					previewSrcList.push(this.ftpDownload + item.path);
				});
				console.log('-=-=-',this.currentFileList)
				this.dataBind[this.nameBind] = name.join(',');
				this.dataBind[this.pathBind] = path.join(',');
				this.view.previewSrcList = previewSrcList;

				this.$emit('change', {
					fileIds:fileIds,
					[this.nameBind]: name.join(','),
					[this.pathBind]: path.join(','),

				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.upload-file {
		.upload-btn {
			.btn {
				width: auto;
				display: inline-block;
				position: relative;
				overflow: hidden;
			}

			.file-input {
				width: 0;
				height: 0;
				position: absolute;
				/*top: 0;*/
				/*left: 0;*/
				/*right: 0;*/
				/*bottom: 0;*/
				opacity: 0;
				z-index: 9999;
			}
		}

		.file-list {
			max-width: 500px;
			width: 100%;

			.file-item {
				width: 100%;
				height: 25px;
				line-height: 25px;
				box-sizing: border-box;
				padding-right: 25px;
				position: relative;
				margin-top: 10px;

				i {
					color: #909399;
				}
			}

			.file-msg {
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}

			.file-name {
				font-size: 14px;
				color: #888;
				display: inline-block;
				line-height: 25px;
			}

			.right-icon {
				width: 20px;
				position: absolute;
				top: 0;
				right: 0;
				cursor: pointer;

				&:hover {
					i {
						&:first-child {
							display: none;
						}

						&:last-child {
							display: inline-block;
						}
					}
				}

				i {
					position: absolute;
					top: 0;
					left: 0;
					line-height: 25px;
					display: inline-block;

					&:first-child {
						color: #67c23a;
					}

					&:last-child {
						display: none;
					}
				}
			}
		}
	}

	.upload-image {
		width: 100%;

		.upload-btn {
			width: 100px;
			height: 100px;
			text-align: center;
			line-height: 100px;
			border: 1px solid #eee;
			border-radius: 5px;
			position: relative;
			float: left;
			margin-right: 10px;
			margin-bottom: 10px;
			overflow: hidden;

			.img {
				width: 100%;
				height: 100%;
			}
		}

		.signle-upload-btn {
			float: none;
			position: relative;

			.top-delete {
				width: 25px;
				height: 25px;
				position: absolute;
				right: 0;
				top: 0;
				z-index: 1;

				img {
					width: 100%;
					display: block;
				}
			}

			&:hover {
				.opera {
					visibility: visible;
					opacity: 1;
				}
			}

			.opera {
				width: 100%;
				height: 100%;
				text-align: center;
				position: absolute;
				top: 0;
				left: 0;
				z-index: 1;
				background: rgba(0, 0, 0, .5);
				visibility: hidden;
				opacity: 0;
				transition: all .5s;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
			}

			.delete,
			.view {
				width: 100%;
				height: 40%;
				display: flex;
				align-items: center;
				justify-content: center;

				i {
					color: #fff;
					font-size: 22px;
					line-height: 1;
					cursor: pointer;
				}
			}
		}

		.add-image {
			width: 50px;
			height: 50px;
			display: inline-block;
			vertical-align: middle;
		}

		.loading-image {
			width: 30px;
			height: 30px;
			display: inline-block;
			vertical-align: middle;
		}

		.img-list {
			zoom: 1;

			&:after {
				content: '';
				display: block;
				visibility: hidden;
				height: 0;
				clear: both;
			}
		}

		.img-item {
			width: 100px;
			height: 100px;
			border-radius: 3px;
			overflow: hidden;
			float: left;
			margin-right: 10px;
			margin-bottom: 10px;
			box-shadow: 1px 0px 5px 2px rgba(0, 0, 0, .2);
			position: relative;
			cursor: pointer;

			&:hover {
				.opera {
					visibility: visible;
					opacity: 1;
				}
			}

			.img {
				width: 100%;
				height: 100%;
			}

			.delete {
				width: 25px;
				height: 25px;
				position: absolute;
				right: 0;
				top: 0;
				z-index: 1;

				img {
					width: 100%;
				}
			}
		}

		.image-input {
			opacity: 0;
			width: 100%;
			height: 100%;
			position: absolute;
			left: 0;
			top: 0;
			cursor: pointer;
		}

		.image-input.he50 {
			height: 50%;
		}
	}
</style>
